<template>
  <div class="directorys-add">
    <el-dialog :title="`${data.id?'新增':'修改'}目录`" :visible.sync="showDialog" width="400px">
      <el-form ref="form" :model="formModel" :rules="rules" size="small" label-width="80px">
        <el-form-item label="所属学科" v-if="!$route.query.id" prop="subjectID">
        <el-select v-model="formModel.subjectID" style="width:100%">
           <el-option
              v-for="item in subjectOptions"
              :value="item.value"
              :label="item.label"
              :key="item.value"
            ></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="formModel.directoryName" placeholder="请输入目录名称"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="addClick">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys'
import { simple as subjectList } from '@/api/hmmm/subjects'
export default {
  name: 'DirectorysAdd',
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      showDialog: false,
      formModel: {
        id: '',
        subjectID: '',
        directoryName: ''
      },
      rules: {
        subjectID: [
          { type: 'number', message: '请选择所属学科', tirgger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', tirgger: 'blur' }
        ]
      },
      // 下拉菜单数据
      subjectOptions: []
    }
  },
  // 学科下拉选项
  async created () {
    const { data: subjectArr } = await subjectList()
    this.subjectOptions = subjectArr
  },
  methods: {
    open () {
      this.showDialog = true
      if (this.data.id) {
        const { id, subjectID, directoryName } = this.data
        this.formModel = { id, subjectID, directoryName }
        console.log(this.formModel)
      }
    },
    // 确认功能 新增/修改
    addClick () {
      console.log(1)
      this.$refs.form.validate(async (flag) => {
        if (!flag) return
        if (!this.data.id) {
          // 新增
          await add(this.formModel)
        } else {
          // 修改
          this.formModel.id = this.data.id
          await update(this.formModel)
        }
        this.$message.success('操作成功')
        this.$emit('newdataList')
        this.showDialog = false
      })
    }

  }
}
</script>

<style scoped lang='less'></style>
